package cn.jietuo.juc.c_007_reentrant;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/8
 * @description:
 * 计数信号量实践
 * 常用于限制可以访问某些资源的线程数量
 */
public class T08_Semaphore {
    public static void main(String[] args) {
        // 信号量，只允许2个线程同时访问
        Semaphore semaphore = new Semaphore(2);

        new Thread(()->{
            try {
                semaphore.acquire();
                // 从此信号量获取给定数目许可
//                semaphore.acquire(2);
                System.out.println("t1 start");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("t1 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();

        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("t2 start");
                TimeUnit.SECONDS.sleep(6);
                System.out.println("t2 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();
    }
}
